// ES modules
import {SocketD} from "@noear/socket.d"

export const session = await SocketD.createClient("sd:ws://localhost:31433/dataPump-api/mvc").open()

const ctxPath = "/dataPump-api"
let debug = true
export const setDebug = (d)=>{
    debug = d
}
export const getDebug = ()=>{
    return debug
}

export const decodeData = (data,charset)=>{

}

export const sendAndRequest = (url,data)=>{
    if(getDebug()){
        console.log('请求url:',ctxPath+url)
        console.log('请求事件:',url)
        console.log('请求数据:',data)
    }
    const entity = SocketD.newEntity(JSON.stringify(data)).metaPut("Content-Type","text/json");
    return session.sendAndRequest(ctxPath+url,  entity)
}

export const chainSendAndRequest = (url,data)=>{
    if(getDebug()){
        console.log('请求url:',ctxPath+url)
        console.log('请求事件:',url)
        console.log('请求数据:',data)
    }

    return new Promise(function (resolve, reject) {
        const entity = SocketD.newEntity(JSON.stringify(data)).metaPut("Content-Type","text/json");
        session.sendAndRequest(ctxPath+url,  entity).thenReply(reply=>{
            // const decoder = new TextDecoder('UTF-8')
            // let json = JSON.parse(decoder.decode(reply.data()?.getArray()));
            let json = JSON.parse(reply.dataAsString())
            if(getDebug()){
                console.log('返回结果:',reply)
                console.log('解析结果:',json)
            }
            resolve(json)
        }).thenError(error=>{
            console.error('chainSendAndRequest异常：',error)
            reject(error)
         });
    });

    
}